<?php
namespace Modules\Backstage\Controllers;

class UserOrderController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');

		$service = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($service['code'] != 0) {
			$this -> response -> setJsonContent(['code'=>-1,'msg'=>$service['message'] ]) -> send();
			exit;
		}

		$this -> account::getAclInstance() -> check($this, $dispatcher, $service['model'] -> roles_id);
	}


	public function pagerAction() {
		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> user::getOrderLogicInstance() -> pager([], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function statusAction() {
		$put = $this -> request -> getPut();
		$userOrderId = $put['user_order_id'];
		unset($put['user_order_id']);

		$this -> db -> begin();
		try {
			switch($put['status']) {
				case 9:
				case '9':
					$orderService = $this -> user::getOrderServiceInstance() -> update($userOrderId, $put);
					if($orderService['code'] != 0) { throw new \Exception($orderService['message']); }
					//if($orderService['code'] != 0) { throw new \Exception('收货失败'); }
					break;
				default:
					if($orderService['code'] != 0) { throw new \Exception('未知操作'); }
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		switch($put['status']) {
			case 9:
			case '9':
				return $this -> response -> setJsonContent(['code'=>0,'msg'=>'发货成功']);
			default:
				return $this -> response -> setJsonContent(['code'=>0,'msg'=>'未知操作']);
		}
	}
}